#encoding: utf-8

=begin

更新商家的统计数据，包括：收藏粉丝数

=end

load 'rds_api.rb'

def get_active_merchants
  merchants = []
  sql = "select * from crmeb.eb_system_store"# where is_show = 1;" #测试时用的每次重置模式
  queryRds(sql).each { |q| merchants += [q] }
  return merchants
end

def update_follow_count merchant
  sql = "update crmeb.eb_system_store set follow_count = ( 
      SELECT count(*) FROM crmeb.eb_store_product_relation where product_id = #{merchant['id']} and category = 'merchant' 
    ) where id = #{merchant['id']};"
  queryRds sql
end

#如果未发现有pid=20的对应mer_id下的记录，为其创建一个新的目录
def update_attachment_category merchant
  mer_id = merchant['id']
  name = merchant['name']
  sql = "select id from crmeb.eb_system_attachment_category where pid = 20 and mer_id = #{mer_id}"
  no_root = true
  queryRds(sql).each do |q| 
    no_root = false
    break
  end
  if no_root
    sql = "insert into crmeb.eb_system_attachment_category(name,pid,mer_id) values('#{@rds.escape name}',20,#{mer_id})"
    queryRds sql
  end
end

def update_all_merchants
  merchants = get_active_merchants
  merchants.each do |merchant|
    update_follow_count merchant
    update_attachment_category merchant
  end
  puts "done. #{merchants.size}"
end

#@rds = @rds_fcdev
#update_all_merchants
@rds = @rds_fc
update_all_merchants
